package com.imis.base.interceptor;

import com.imis.base.constant.CommonConstant;
import com.imis.base.constant.DataBaseConstant;
import com.imis.base.util.ConvertUtils;
import com.imis.base.util.CurrentUserUtils;
import com.imis.module.system.model.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

/**
 * <p>
 * MybatisInterceptor<br>
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2020年03月31日 16:50
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    /**
     * 插入操作执行的数据构建
     *
     * @param parameter -
     * @param sysUserVO -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/8/3 14:53
     */
    private void doInsert(Object parameter, SysUserVO sysUserVO) {
        Field[] fields = ConvertUtils.getAllFields(parameter);
        for (Field field : fields) {
            try {
                // 注入创建者
                if (DataBaseConstant.CREATE_BY.equals(field.getName())) {
                    field.setAccessible(true);
                    Object local_createBy = field.get(parameter);
                    field.setAccessible(false);
                    if (ConvertUtils.isEmpty(local_createBy)) {
                        field.setAccessible(true);
                        if (sysUserVO != null) {
                            // 登录人编号
                            field.set(parameter, Long.valueOf(sysUserVO.getId()));
                        } else {
                            // 默认值
                            field.set(parameter, 0L);
                        }
                        field.setAccessible(false);
                    }
                }
                // 注入创建时间
                if (DataBaseConstant.CREATE_TIME.equals(field.getName())) {
                    field.setAccessible(true);
                    Object local_createDate = field.get(parameter);
                    field.setAccessible(false);
                    if (ConvertUtils.isEmpty(local_createDate)) {
                        field.setAccessible(true);
                        field.set(parameter, java.time.LocalDateTime.now());
                        field.setAccessible(false);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 更新操作执行的数据构建
     *
     * @param parameter -
     * @param sysUserVO -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/8/3 14:53
     */
    private void doUpdate(Object parameter, SysUserVO sysUserVO) {
        // 调整参数
        if (parameter instanceof MapperMethod.ParamMap) {
            MapperMethod.ParamMap<?> p = (MapperMethod.ParamMap<?>) parameter;
            if (p.containsKey(CommonConstant.ENTITY)) {
                parameter = p.get(CommonConstant.ENTITY);
            } else {
                parameter = p.get("param1");
            }
        }
        // 参数不为空
        if (ConvertUtils.isNotEmpty(parameter)) {
            Field[] fields = ConvertUtils.getAllFields(parameter);
            for (Field field : fields) {
                try {
                    if (DataBaseConstant.UPDATE_BY.equals(field.getName())) {
                        if (sysUserVO != null) {
                            // 登录人编号
                            field.setAccessible(true);
                            field.set(parameter, Long.valueOf(sysUserVO.getId()));
                            field.setAccessible(false);
                        }
                    }
                    if (DataBaseConstant.UPDATE_TIME.equals(field.getName())) {
                        field.setAccessible(true);
                        // 修改时间
                        field.set(parameter, java.time.LocalDateTime.now());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    /**
     * mybatis拦截器执行方法
     *
     * @param invocation - 调用
     * @return Object -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/8/3 14:45
     */
    @Override
    public Object intercept(Invocation invocation) throws InvocationTargetException, IllegalAccessException {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        // 参数不为空
        if (ConvertUtils.isNotEmpty(parameter)) {
            // 获取请求方法的用户信息
            SysUserVO sysUserVO = CurrentUserUtils.getLoginUser();
            // 插入操作
            if (SqlCommandType.INSERT == sqlCommandType) {
                doInsert(parameter, sysUserVO);
            }
            // 更新操作
            if (SqlCommandType.UPDATE == sqlCommandType) {
                doUpdate(parameter, sysUserVO);
            }
        }
        return invocation.proceed();
    }

    /**
     * 重写 plugin
     *
     * @param target -
     * @return Object -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/8/3 14:48
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * 重写 setProperties
     *
     * @param properties -
     * @return Object -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/8/3 14:48
     */
    @Override
    public void setProperties(Properties properties) {

    }

}
